/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License, version
 * 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.jeecg.netty.sensor.nettyserver;

import javax.annotation.Resource;

import org.jeecg.glr.service.IGlrSensorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 *
 * <p>
 * Description: 服务端处理请求类
 * </p>
 *
 * @author <a href="mailto: xiebin@54604344@qq.com">xiebin</a>
 * @version $Revision$
 */
@Sharable
@Component
public class SensorNettyServerHandler extends ChannelInboundHandlerAdapter {

	private static final Logger logger = LoggerFactory.getLogger(SensorNettyServerHandler.class);

	String key = "";// 主控唯 一标识

	@Resource
	IGlrSensorService glrSensorService;

	/**
	 *
	 * <p>
	 * 监听是否有客户端连接。
	 * </p>
	 *
	 * @param ctx
	 * @throws Exception
	 * @author:xiebin 2017-3-11
	 * @update: [updatedate] [changer][change description]
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		ctx.channel().closeFuture().addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isDone()) {
					// 移除掉线的channel
					glrSensorService.removeOffLineGataWay(ctx);
				}
			}
		});
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object objMsg) throws Exception {
		try {
			ByteBuf buf = (ByteBuf) objMsg;
			glrSensorService.dealData(buf, ctx.channel());
			// logger.info("在线的传感器:--->"+SenSorConfigConsts.senSorchannelMap.keySet());
		//	ctx.flush();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				ReferenceCountUtil.release(objMsg);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.error("传感器服务器异常..。。。。。Sensor。。。。。。。。.{}", cause.getMessage());
		//cause.printStackTrace();
		ctx.close();
	}

}
